package Euler37;

import java.util.*;
import ReusableCode.*;

public class TruncatablePrimes {
	public static void main(String[] args) {
		int max = 1000000;
		List<Integer> primes = PrimeFunctions.GetPrimes(max);
		Set<Integer> primesHash = PrimeFunctions.GetPrimesHash(max);
		long sum = 0;
		
		for(int i = 0; i < primes.size(); i++)
		{
			int num = primes.get(i);
			if(num>10 && isTruncatablePrime(num, primesHash))
			{
				sum+=num;
				System.out.println(num);
			}
		}
		
		System.out.println("Sum is: " + sum);
	}
	
	static boolean isTruncatablePrime(int num, Set<Integer> primes)
	{
		int numsR[] = MathFunctions.getDigits(num);
		int numsF[] = MathFunctions.reverseArray(numsR.clone());
		return isTruncatablePrime(Arrays.copyOf(numsF, numsF.length-1), true, primes) && isTruncatablePrime(Arrays.copyOf(numsR, numsR.length-1), false, primes);
	}
	
	static boolean isTruncatablePrime(int nums[], boolean isRight,Set<Integer> primes)
	{
		int length = nums.length;
		
		if(length==1)
		{
			if(primes.contains(nums[0]))
			{
				return true;
			}
		}
		else if(length>1)
		{
			int num = 0;
			int sub[] = new int[length-1];
			
			for(int i = 0; i < length; i++)
			{
				if(i<(length-1))
				{
					sub[i] = nums[i];
				}
				
				if(isRight)
				{
					num += nums[i] * Math.pow(10, length-1-i);
				}
				else
				{
					num += nums[i] * Math.pow(10, i);
				}
			}
			
			if(primes.contains(num))
			{
				return isTruncatablePrime(sub, isRight, primes);
			}
			else
			{
				return false;
			}
		}
		
		return false;
	}
}
